<?php


namespace phpboot\doctrine;


use Doctrine\ORM\Tools\Setup;

class EntityManager
{
    private $db_config = [];


    /** @var EntityManager[] */

    private static $_instance = [];

    private static $default_db_config = [
        'isDevMode' => true,
        'proxyDir' => null,
        'cache' => null,
        'useSimpleAnnotationReader' => false,
        'driver' => 'pdo_mysql',
        'type' => 'mysql',
        'host' => '127.0.0.1',
        'dbname' => '',
        'user' => 'root',
        'password' => 'root',
        'port' => 3306,
        'prefix' => '',
        'paths' => [],
    ];

    private $_entityManager;

    private function __construct($db_config)
    {
        $db_config = array_merge(self::$default_db_config, $db_config);
        $config = Setup::createAnnotationMetadataConfiguration($db_config["paths"], $db_config['isDevMode'], $db_config["proxyDir"], $db_config['cache'], $db_config['useSimpleAnnotationReader']);
        $conn = array(
            'driver' => $db_config["driver"],
            'type' => $db_config["mysql"],
            'host' => $db_config["host"],
            'dbname' => $db_config["dbname"],
            'user' => $db_config["user"],
            'password' => $db_config["password"],
            'port' => $db_config["port"],
            'prefix' => $db_config["prefix"],
            'charset' => $db_config["charset"],
            'paths' => $db_config["paths"]
        );
        foreach ($db_config["paths"] as $path) {
            if (!is_dir($path)) mkdir($path, 777, true);
        }
        $config->addCustomStringFunction("REGEXP", RegexpPdomysql::class . preg_replace("/_([a-z])/", '$1', ucfirst($db_config["driver"])));
        $this->_entityManager = \Doctrine\ORM\EntityManager::create($conn, $config, $this->getPrefixEvent($db_config["prefix"]));
        $this->db_config = $db_config;
    }

    private function getPrefixEvent($prefix)
    {
        $evm = new \Doctrine\Common\EventManager;
        $tablePrefix = new TablePrefix($prefix);
        $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
        return $evm;
    }


    public function getEntityManager()
    {
        return $this->_entityManager;
    }

    public static function getManager($db_config, $key = "default")
    {
        if (!isset(self::$_instance[$key])) {
            self::$_instance[$key] = new static($db_config);
        }
        return self::$_instance[$key]->getEntityManager();
    }

    public static function getConfig($key = "default")
    {
        return isset(self::$_instance[$key]) ? self::$_instance[$key]->getDBConfig() : [];
    }

    public function getDBConfig()
    {
        return $this->db_config;
    }


}
